package com.sniff.atp.service.common;

import cn.hutool.json.JSONObject;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.devops20210625.AsyncClient;
import com.aliyun.sdk.service.devops20210625.models.ListProjectsRequest;
import com.aliyun.sdk.service.devops20210625.models.ListProjectsResponse;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;

import java.time.Duration;
import java.util.concurrent.CompletableFuture;

/**
 * @BelongsProject: sniff-atp
 * @BelongsPackage: com.sniff.atp.service.common
 * @Author: zxy
 * @CreateTime: 2024-07-12 15:58
 * @Description:
 * @Version: 1.0
 */
public class AliyunOpenApi {


    private static final String accessKeyId = "LTAI5tF8nEMMg1rh6kAZjgj7";
    private static final String accessKeySecret = "lL5L87T05o98rweT9PzQm7lOqwmP2e";


    public static void main(String[] args) throws Exception {

        // HttpClient Configuration
//        HttpClient httpClient = new ApacheAsyncHttpClientBuilder()
//                .connectionTimeout(Duration.ofSeconds(10)) // Set the connection timeout time, the default is 10 seconds
//                .responseTimeout(Duration.ofSeconds(10)) // Set the response timeout time, the default is 20 seconds
//                .maxConnections(128) // Set the connection pool size
//                .maxIdleTimeOut(Duration.ofSeconds(50)) // Set the connection pool timeout, the default is 30 seconds
//                // Configure the proxy
//                .proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("<your-proxy-hostname>", 9001))
//                        .setCredentials("<your-proxy-username>", "<your-proxy-password>"))
//                // If it is an https connection, you need to configure the certificate, or ignore the certificate(.ignoreSSL(true))
//                .x509TrustManagers(new X509TrustManager[]{})
//                .keyManagers(new KeyManager[]{})
//                .ignoreSSL(false)
//                .build();

        // Configure Credentials authentication information, including ak, secret, token
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set.
                .accessKeyId(accessKeyId)
                .accessKeySecret(accessKeySecret)
                //.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // use STS token
                .build());

        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou") // Region ID
//                .httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                // Endpoint 请参考 https://api.aliyun.com/product/devops
                                .setEndpointOverride("devops.cn-hangzhou.aliyuncs.com")
//                        .setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();

        // Parameter settings for API request
        ListProjectsRequest listProjectsRequest = ListProjectsRequest.builder()
                .organizationId("600142d957a5c7b95a429faa")
                .category("Project")
                .maxResults(10L)
                // Request-level configuration rewrite, can set Http request parameters, etc.
//                .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();

        // Asynchronously get the return value of the API request
        CompletableFuture<ListProjectsResponse> response = client.listProjects(listProjectsRequest);


        System.out.println("************************************************");
        System.out.println(response);


        // Synchronously get the return value of the API request
        ListProjectsResponse resp = response.get();

        System.out.println("***********************************************");
        System.out.println(resp);


        System.out.println("***********************************************");
        System.out.println(new Gson().toJson(resp));

        JSONObject entries = new JSONObject(new Gson().toJson(resp));
        System.out.println(entries.getJSONObject("body").getJSONArray("projects").getJSONObject(0));



        // Asynchronous processing of return values
        /*response.thenAccept(resp -> {
            System.out.println(new Gson().toJson(resp));
        }).exceptionally(throwable -> { // Handling exceptions
            System.out.println(throwable.getMessage());
            return null;
        });*/

        // Finally, close the client
        client.close();
    }
}
